﻿#if DEBUG
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Messaging;
using JustinAngel.Neurons.Framework;
using JustinAngel.Neurons.Framework.Messages;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Media;
using JustinAngel.Neurons.Framework.Helpers;

namespace JustinAngel.Neurons.Services
{
    public class PrintScreenService : IAppService
    {
        private const bool TakePrintScreenOn5SecondsTapAndHold = false;

        public void StartService()
        {
            if (TakePrintScreenOn5SecondsTapAndHold)
            {
                DispatcherTimerHelper.On(TimeSpan.FromSeconds(10),
                    () =>
                    {
                        var rootFrame = Application.Current.RootVisual.As<PhoneApplicationFrame>();
                        rootFrame.ManipulationStarted += new EventHandler<ManipulationStartedEventArgs>(rootFrame_ManipulationStarted);
                        rootFrame.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(rootFrame_ManipulationCompleted);
                    });
            }
        }


        private void rootFrame_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            if ((DateTime.Now - _lastManipilationStarted).TotalSeconds >= 5)
            {
                SavePrintScreenToMediaLibrary();
            }
        }

        private DateTime _lastManipilationStarted = DateTime.Now;
        void rootFrame_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            _lastManipilationStarted = DateTime.Now;
        }

        void SavePrintScreenToMediaLibrary()
        {
            WriteableBitmap bmp = new WriteableBitmap(480, 800);
            bmp.Render(Application.Current.RootVisual, null);
            bmp.Invalidate();

            using (MediaLibrary library = new MediaLibrary())
                library.SavePicture("Neurons Print Screen " + DateTime.Now.ToFileTimeUtc(), EncodeToJpeg(bmp));
        }

        //http://www.silverlightplayground.org/post/2010/10/15/WP7-Fast-Tips-Load-(decode)-and-Save-(encode)-Jpeg-files.aspx
        public byte[] EncodeToJpeg(WriteableBitmap wb)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                // this is Extensions.SaveJpeg() method
                wb.SaveJpeg(stream, wb.PixelWidth, wb.PixelHeight, 0, 90);
                return stream.ToArray();
            }
        }

        public void StopService()
        {
        }
    }
}
#endif
